import { getAll } from '@/api/dict'

const dict = {
  state: {
    dict: JSON.parse(localStorage.getItem('dict')),
    dictIndex: JSON.parse(localStorage.getItem('dictIndex')),
  },

  mutations: {
    SET_DICT: (state, dict) => {
      state.dict = dict
    },
    SET_DICT_INDEX: (state, dictIndex) => {
      state.dictIndex = dictIndex
    }
  },

  actions: {
    // 获取菜单信息
    getAllDict({ commit, state }, ifForceGet) {
      if (!state.dict || ifForceGet) {
        return new Promise((resolve, reject) => {
          getAll().then(res => {
            let simple = {}
            let complex = {}
            let simpleIndex = {}
            let complexIndex = {}
            res.data.simple.forEach(e => {
              if (!simple[e.regionCode]) {
                simple[e.regionCode] = []
                simpleIndex[e.regionCode] = {}
              }
              simple[e.regionCode].push(e)
              simpleIndex[e.regionCode][e.itemCode] = e.itemName
            })
            res.data.complex.forEach(e => {
              if (!complex[e.regionCode]) {
                complex[e.regionCode] = []
                complexIndex[e.regionCode] = {}
              }
              complex[e.regionCode].push(e)
              complexIndex[e.regionCode][e.itemCode] = e.itemName
            })
            let dict = {
              simple: simple,
              complex: complex
            }
            let dictIndex = {
              simple: simpleIndex,
              complex: complexIndex
            }
            localStorage.setItem('dict', JSON.stringify(dict))
            localStorage.setItem('dictIndex', JSON.stringify(dictIndex))
            commit('SET_DICT', dict)
            commit('SET_DICT_INDEX', dictIndex)
            resolve()
          }).catch(err => {
            reject(err)
          })
        })
      }
    }
  }
}

export default dict
